package com.game.gateway.channel;

import com.game.framework.common.error.EventExecutorGroup;
import io.netty.channel.Channel;
import io.netty.util.concurrent.EventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ServerChannelGroup {

	private Map<Object, ServerChannelContext> serverChannelContextMap = new HashMap<>();
	private EventExecutor executor;
	private EventExecutorGroup executorGroup;
	
	private ApplicationContext applicationContext;

	public ServerChannelGroup(EventExecutorGroup executorGroup, ApplicationContext context) {
		this.executor = executorGroup.select(0);
		this.executorGroup = executorGroup;
		this.applicationContext = context;
	}

	private void executeTask(Runnable task) {
		this.executor.execute(() -> {
			try {
				task.run();
			} catch (Throwable e) {
				log.error("执行任务失败", e);
			}
		});
	}

//	public void gameChannelConsumer(Object key, Consumer<GameServerContext> consumer) {
//		this.executeTask(() -> {
//			GameServerContext gameServerContext = this.gameChannelMap.get(key);
//			if (gameServerContext != null) {
//				consumer.accept(gameServerContext);
//			} else {
//				log.debug("不存在{} 对应的GameChannel，创建新的GameChannel", key);
//				gameServerContext = new GameServerContext(springContext,executorGroup.select(key), key.toString());
//				this.gameChannelMap.put(key, gameServerContext);
//				consumer.accept(gameServerContext);
//			}
//		});
//	}
	

//	public void removeGameChannel(Object key) {
//		this.executeTask(() -> {
//			gameChannelMap.remove(key);
//		});
//	}
//
	public Channel getChannel(long serverId) {
		return serverChannelContextMap.get(serverId).getChannel();
	}
}
